import React from 'react';
import './todo-style.css';

export default class Todo extends React.Component {
 constructor({ data, finished }) {
   super();
   
   this.state = Object.assign({}, data);
   this.onFinish = finished;
 }
 finish() {
   if (!this.state.finished) {
     this.setState({
       finished: true
     });
   }
   this.onFinish(this.state.time);
 }
 get time() {
  let date = new Date(parseInt(this.state.time));

  let now = new Date();

  let hours = date.getHours()>=10?date.getHours():('0'+date.getHours());
  let minutes = date.getMinutes()>=10?date.getMinutes():('0'+date.getMinutes());

  if (now.getFullYear() !== date.getFullYear()) {
    return date.getFullYear() + '年' + (date.getMonth() + 1) + '月' + (date.getDate() + 1) + '日 ' + hours + ':' + minutes
  } else {
    if (now.getMonth() === date.getMonth() && Math.abs(now.getDate() - date.getDate()) <= 2) {
      let rili = ['今天 ', '昨天 ', '前天 '];
      return rili[Math.abs(now.getDate() - date.getDate())] + hours + ':' + minutes
    } else {
      return (date.getMonth() + 1) + '月' + (date.getDate() + 1) + '日 ' + hours + ':' + minutes
    }
  }
 }
 render() {
   return (
    <section className={this.state.finished ? 'todo todo-finished': 'todo todo-unfinished'}>
      <h1>{this.state.title}</h1>
      <time>{this.time}</time>
      <p>{this.state.content}</p>
      <button onClick={this.finish.bind(this)}>{this.state.finished ? '已完成': '未完成'}</button>
    </section>
  )
 }
}